#include "send_response_aw.h"
#include "../net/coro_tcp.h"
#include "../http/message_details.h"

namespace wilson::http
{
    coro::task<size_t> 
    send_response_func(
        coro::epoll_suspend_manager& esm, 
        net::tcp_io& io, 
        server::response resp, 
        ::std::error_code* ec)
    {
        auto [yes, path] = resp.attached_file();
        auto before_body = resp.to_payload();
        size_t result{};
        result = co_await net::send_aw{ esm, io, before_body, 0, ec };
        if (ec && *ec) co_return result;
        if (yes) 
        {
            if (ec) *ec = {};
            result += co_await net::send_file_aw{ esm, io, path, 0, ec };
            if (ec && *ec) co_return result;
            if (ec) *ec = {};

            ::std::string_view double_crlf = CRLF CRLF;
            result += co_await net::send_aw{ esm, io, double_crlf, 0, ec };
        }

        co_return result;
    }
}
